package com.synergy.stockflow.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.synergy.stockflow.constant.ResultCode;
import com.synergy.stockflow.model.Result;
import com.synergy.stockflow.product.entity.OrderSteps;
import com.synergy.stockflow.product.service.OrderStepsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/orderSteps")
public class OrderStepsController {
    @Autowired
    private OrderStepsService orderStepsService;
    @GetMapping("/index")
    public Result<Page<OrderSteps>> page(@RequestParam(name = "current", defaultValue = "1") int current,
                                         @RequestParam(name = "size", defaultValue = "5") int size,
                                         String processId
                                         ){
        {
            QueryWrapper<OrderSteps> query =new QueryWrapper<>();
            query.lambda().eq(OrderSteps::getProcessId,processId);
            Page<OrderSteps> page = new Page<>(current,size);
            page = orderStepsService.page(page,query);
            return Result.success(page);
        }
    }
    @PostMapping("insert")
    public Result insert(@RequestBody OrderSteps orderSteps){
        QueryWrapper<OrderSteps> query = new QueryWrapper<>();
        if (orderSteps.getSequenceId() != null && orderSteps.getSequenceId()> 0) {
            query.lambda().eq(OrderSteps::getSequenceId, orderSteps.getSequenceId());
        }
        Page<OrderSteps> page = new Page<>(1, 10000);
        Page<OrderSteps> page1 = orderStepsService.page(page, query);
        if (page1 == null || page1.getRecords().size() == 0) {
            orderStepsService.save(orderSteps);
            return Result.success(orderSteps);
        }
        return Result.error(ResultCode.BUSINESS_EXCEPTION.value(), "步骤序号已存在");

    }
    @PutMapping("update")
    public Result update(@RequestBody OrderSteps orderSteps){
        System.out.println(orderSteps);
        orderStepsService.updateById(orderSteps);
        return Result.success(orderSteps);
    }
    @DeleteMapping("/delete")
    public Result delete(@RequestBody List<OrderSteps> orderSteps){

        for (OrderSteps orderStep:orderSteps){
            System.out.println(orderStep);
        }

        for(OrderSteps orderStep:orderSteps){
            orderStepsService.removeById(orderStep.getStepId());
        }
        return Result.success(orderSteps);
    }
}
